package com.naiterui.ehp.bs.weixin.config;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.naiterui.ehp.bs.weixin.service.IAccessTokenService;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeAdd;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeAddResult;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeInfo;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeList;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeProperties;
import com.naiterui.ehp.bs.weixin.wechat.WeChatApiUtil;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 小程序订阅通知模板配置
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/5/20 18:00
 **/
@Slf4j
@Component
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "subscribe")
public class SubscribeConfig implements InitializingBean {

    private List<SubscribeProperties> template;
    private final IAccessTokenService accessTokenService;

    /**
     * 模板配置集合   key:label;value:模板配置属性
     *
     * @return
     */
    public Map<String, SubscribeProperties> templateMap() {
        return Optional.ofNullable(template)
                .map(t -> t.stream().collect(Collectors.toMap(SubscribeProperties::getLabel, Function.identity())))
                .orElse(Collections.emptyMap());
    }

    public List<SubscribeProperties> getTemplate() {
        return template;
    }

    public void setTemplate(List<SubscribeProperties> template) {
        this.template = template;
    }

    @Override
    public void afterPropertiesSet() {
        try {
            SubscribeList subscribeList = WeChatApiUtil.getSubscribeList(accessTokenService.accessToken());
            Map<String, String> templateMap = Optional.ofNullable(subscribeList.getData())
                    .map(list -> list.stream().collect(Collectors.toMap(SubscribeInfo::getTitle, SubscribeInfo::getPriTmplId))).orElse(Collections.emptyMap());
            template.forEach(t -> {
                String templateId = templateMap.get(t.getTitle());
                if (templateId == null) {
                    SubscribeAdd subscribeAdd = SubscribeAdd.builder().tid(t.getTId()).kidList(t.getKidList()).sceneDesc(t.getSceneDesc()).build();
                    SubscribeAddResult result = WeChatApiUtil.setSubscribeTemplate(accessTokenService.accessToken(), subscribeAdd);
                    log.info("SubscribeConfig Initializing AddTemplate ; request={} ,result={}", subscribeAdd, result);
                    templateId = result.getPriTmplId();
                    if (templateId != null) {
                        templateMap.put(t.getTitle(), templateId);
                    }
                }
                t.setTemplateId(templateId);
            });
            log.info("SubscribeConfig Initializing Result {}", JSONUtil.toJsonStr(template));
        } catch (Exception e) {
            log.warn("SubscribeConfig Initializing ERROR ", e);
        }
    }
}